﻿/// <reference path="utils.js" />

/**
* 模块名：共通脚本
* 程序名: 通用方法common.js
* Copyright(c) 2013-2015 wanglei[ wanglei9455@126.com ] 
**/

var com = {};
com.vm = {};


com.ajax = function (options) {
    options = $.extend({
        showLoading: true
    }, options);

    var ajaxDefaults = {
        type: 'POST',
        dataType: 'json',

        error: function (e) {
            var msg = e.responseText;
            var ret = msg.match(/^{\"Message\":\"(.*)\",\"ExceptionMessage\":\"(.*)\",\"ExceptionType\":.*/);
            if (ret != null) {
                msg = (ret[1] + ret[2]).replace(/\\"/g, '"').replace(/\\r\\n/g, '<br/>').replace(/dbo\./g, '');
            }
            else {
                try { msg = $(msg).text() || msg; }
                catch (ex) { }
            }

            com.message('error', msg);
        }
    };

    if (options.showLoading) {
        ajaxDefaults.beforeSend = $.showLoading;
        ajaxDefaults.complete = $.hideLoading;
    }

    $.ajax($.extend(ajaxDefaults, options));
};


com.dialogObj = {
    title: 'New Dialog',
    width: 400,
    height: 220,
    closed: false,
    cache: false,
    modal: true,
    iconCls: 'icon-key',
    resizable: true
};


//将form表单序列化成一个对象，com.serializeObj("Id")
com.serializeObj = function (form) {

    var o = {};
    $form = $("#" + form);
    $.each($form.serializeArray(), function (index) {
        if (o[this['name']]) {
            o[this['name']] = o[this['name']] + "," + this['value'];
        } else {
            o[this['name']] = this['value'];
        }
    });
    return o;
};




//将form表单序列化成一个查询条件数组（测试）
com.serializeSearchArray = function (form) {
    var o = {};
    var newArray = [];
    $form = $("#" + form);
    var array = $form.serializeArray();

    $.each($form.serializeArray(), function (index) {
        // console.log($("#" + this["name"]).attr("data-cp"));
        var Operator = $("#" + this["name"]).attr("data-cp");
        if (this["value"] != "" && this["value"] != null) {
            newArray.push({ Field: this["name"], Value: this["value"], Operator: Operator });
        }
    });
    // console.log(newArray);
    var str = JSON.stringify(newArray);
    o.searchData = str;
    return o;

};


//将form表单序列化成一个查询条件数组（测试）
com.serializeSearchArray1 = function (form) {
    var newArray = [];
    $form = $("#" + form);
    var array = $form.serializeArray();

    $.each($form.serializeArray(),
        function (index) {
            // console.log($("#" + this["name"]).attr("data-cp"));
            var Operator = $("#" + this["name"]).attr("data-cp");
            if (this["value"] != "" && this["value"] != null) {
                newArray.push({ Field: this["name"], Value: this["value"], Operator: Operator });
            }
        });
    // console.log(newArray);
    var str = JSON.stringify(newArray);
    return str;

};



//弹messagee
com.message = function (type, message, callback) {
    switch (type) {
        case "success":
            parent.$.messager.show({
                title: '消息',
                msg: message
            });
            break;
        case "error":
            if (parent == window) return alert(message);
            parent.$.messager.alert('错误', message);
            break;
        case "warning":
            if (parent == window) return alert(message);
            parent.$.messager.alert('警告', message);
            break;
        case "information":
            parent.$.messager.show({
                title: '消息',
                msg: message
            });
            break;
        case "confirm":
            return parent.$.messager.confirm('确认', message, callback);
    }

    if (callback) callback();
    return null;
};


com.getArrayText = function (obj, value) {
    var strText = "";
    $.each(obj, function () {
        // console.log(this.value)
        if (this.value == value) {
            strText = this.text;
        }
    })
    return strText;
};


com.getArrayTextbySpecField = function (obj, key, value, textKey) {
    var strText = "";
    $.each(obj, function () {
        // console.log(this.value)
        if (this[key] == value) {
            strText = this[textKey];
        }
    })
    return strText;
};


com.getHighSearchList = function () {
    var o = {};
    var highArr = [];
    for (var i = 0; i < 10; i++) {
        var target = com.getSerachObject(i);
        if (target) {
            highArr.push(target);
        }
    }
    o.highSearchData = JSON.stringify(highArr);
    return o;
};


com.getSerachObject = function (index) {
    var searchObj = {};
    searchObj.Left = $("#Left" + index).val();
    searchObj.Field = $("#Field" + index).combobox("getValue");
    searchObj.Operator = $("#Operator" + index).combobox("getValue");
    searchObj.Value = $("#Value" + index).val();
    searchObj.Logic = $("#Logic" + index).combobox("getValue");
    searchObj.Right = $("#Right" + index).val();
    if (searchObj.field != "" && searchObj.operater != "") {
        return searchObj;
    }
    else {
        return null;
    }

};


com.ConCheck = function (tbName) {

    var $tbList = $("#" + tbName);
    var rows = $tbList.datagrid("getSelections");
    if (rows.length > 1) {
        //  var firstRow = rows[0];
        //  var lastRow = rows[rows.length - 1];
        var firstIndex = $tbList.datagrid("getRowIndex", rows[0]);
        var lastIndex = firstIndex;
        for (var i = 0; i < rows.length; i++) {
            var currentIndex = $tbList.datagrid("getRowIndex", rows[i]);
            if (currentIndex < firstIndex) {
                firstIndex = currentIndex;
            }
            if (currentIndex > lastIndex) {
                lastIndex = currentIndex;
            }
        }
        for (var i = firstIndex; i < lastIndex + 1; i++) {
            $tbList.datagrid("checkRow", i)
        }
    }
    else {
        com.message("information", "请选择两条以上的数据");
    }
};


com.get = (function () {
    var url = window.document.location.href.toString();
    var u = url.split("?");
    if (typeof (u[1]) == "string") {
        u = u[1].split("&");
        var get = {};
        for (var i in u) {
            var j = u[i].split("=");
            get[j[0]] = j[1];
        }
        return get;
    } else {
        return {};
    }
})();

// 合并单元格 By cherrow
// 示例：mergeCells("tbList", "ProductionDetailID,ProductName, BottleVolume")
com.mergeCells = function (tableID, colList) {
    var colArray = colList.split(",");
    var tTable = $("#" + tableID);
    var tableRows = tTable.datagrid("getRows");
    var tableRowCnts = tableRows.length;
    if (tableRowCnts < 2) return;
    var mark = 1;
    for (var i = 1; i < tableRowCnts; i++) {
        //以第一个字段为准进行合并
        if (tableRows[i][colArray[0]] == tableRows[i - 1][colArray[0]]) {
            mark += 1;
            for (var j = 0; j < colArray.length; j++) {
                tTable.datagrid('mergeCells', {
                    index: i + 1 - mark,
                    field: colArray[j].trim(),
                    rowspan: mark
                });
            }
        } else {
            mark = 1;
        }
    }
};

com.ConvertLower = function (GasName) {
    var arr = GasName.split('');
    var regNum = /\d+/g;//匹配任意长度数字
    var regWord = /[a-z,A-Z]/g;//匹配任意字母
    var result = "";
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].match(regWord)) {
            result += arr[i];
        }
        else if (arr[i].match(regNum)) {
            result += "<sub>" + arr[i] + "</sub>";
        }
        else {
            result += arr[i];
        }
    }
    return result;
}
com.FillAir = function (DetailData, printIsAir) {
    if (printIsAir == "0") {
        return DetailData;
    }
    else {
        var newData = [];
        for (var i = 0; i < DetailData.length; i++) {
            if (DetailData[i].IsBottom == "0") {

                if (DetailData[i].GasEngName != "O2" && DetailData[i].GasEngName != "N2") {

                    newData.push(DetailData[i])

                }

            }
            else {
                var obj = { GasEngName: "Air", GasChiName: "空气", };
                newData.push(obj);

            }
        }
        return newData;
    }
}

com.geObjBySpecField = function (obj, key, value) {
    var returnObj = {};

    $.each(obj, function () {
        // console.log(this.value)
        if (this[key] == value) {
            returnObj = this;
        }
    })
    return returnObj;
}

//打印字符串中同时处理分子式和单位
com.ConvertLowerAndUper = function (techStr, isPure) {
    var arr = techStr.split(/[\:\;]/g);
    //分子式转换
    var regNum = /\d+/g;//匹配任意长度数字
    var regWord = /[a-z,A-Z]/g;//匹配任意字母
    //浓度及单位转换
    var regUnit = /[m]\d/g;
    var result = "";
    if ("0" === isPure) {
        //混合气体处理
        for (var i = 0; i < arr.length; i++) {
            if (i % 2 == 0) {
                var tempArr = arr[i].split("");
                for (var j = 0; j < tempArr.length; j++) {
                    if (tempArr[j].match(regWord)) {
                        result += tempArr[j];
                    }
                    else if (tempArr[j].match(regNum)) {
                        result += "<sub>" + tempArr[j] + "</sub>";
                    }
                    else {
                        result += tempArr[j];
                    }
                }
                result += ":";
            } else {
                var tempArr = arr[i].split(regUnit);
                if (tempArr.length > 1) {
                    result += tempArr[0] + "m<sup>3</sup>" + ";";
                } else {
                    result += tempArr[0] + ";";
                }
            }
        }
    } else {
        //纯气处理
        for (var i = 0; i < arr.length; i++) {
            if (i % 2 == 0) {
                var tempArr = arr[i].split("");
                for (var j = 0; j < tempArr.length; j++) {
                    if (tempArr[j].match(regWord)) {
                        result += tempArr[j];
                    }
                    else if (tempArr[j].match(regNum)) {
                        result += "<sub>" + tempArr[j] + "</sub>";
                    }
                    else {
                        result += tempArr[j];
                    }
                }
                result += ":" + "&ge;";
            } else {
                var tempArr = arr[i].split(regUnit);
                if (tempArr.length > 1) {
                    result += tempArr[0] + "m<sup>3</sup>" + ";";
                } else {
                    result += tempArr[0] + ";";
                }
            }
        }
    }
    return result;
}
